<template>
    <div style="height: 60px;width: 100%">
        <el-tooltip
                class="box-item"
                effect="dark"
                content="管理展示"
                placement="bottom"
        >
        <el-icon style="float: right;margin-right: 40px" @click="Drawers"><Setting /></el-icon>
        </el-tooltip>
    </div>
    <div class="header">
        <el-date-picker
                v-model="ProductDate"
                type="daterange"
                @calendar-change="selectTime"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY/MM/DD"
                @change="handleChange"
                :disabled-date="pickerOptionsRang"
        />
    </div>
    <el-table :data="tableData" width="48" style="width: 100%" max-height="420px" border :header-cell-style="{background:'rgb(212,216,224)'}">
       <el-table-column
               v-for="(item,index) in tableOne"
               :key="`col_${index}`"
               :prop="item.prop"

               :label="item.label"
               align="center">
           <el-table-column v-if="item.list"
                            v-for="(it,index) in item.list"
                            :key="`col_${index}`"
                            :prop="it.prop"
                            :label="it.label"
                            align="center"></el-table-column>
       </el-table-column>

    </el-table>
    <el-drawer
            v-model="tableShow"
            direction="rtl"
            @open="handleOpen"
            :before-close="handleClose"
            custom-class="demo-drawer"
            size="30%"
    >
        <template #header="{ close, titleId, titleClass }">
                <h4 :id="titleId" :class="titleClass" style="text-align:left">管理展示字段</h4>

        </template>
        <div style="border-top: grey 2px solid;color: grey;margin-top: -20px;width:100%;">
            <p style="text-align:left">选中的字段会在表格中展示</p>
        </div>
        <div class="draggable">
            <el-table
                    ref="Table"
                    row-key="id"
                    :data="tableItems"
                    style="width: 100%"
                    stripe
                    @selection-change="handleSelectionChange"
                    border
            >
                <el-table-column type="selection" width="48" />
                <el-table-column
                        prop="label"
                        label="列表字段名称"
                        align="center"
                >
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #default="scope" >
                        <div style="display: flex;justify-content: space-around">
                            <el-icon @click="MoveUp(scope.$index)" :color="scope.$index ===0?'grey':'blue'"><Top /></el-icon>
                            <el-icon @click="Movedown(scope.$index)" :color="scope.$index ===tableData .length-1?'grey':'blue'"><Bottom /></el-icon>
                            <el-icon class="drag-handle" @mousedown.stop><Rank /></el-icon>
                        </div>

                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex;justify-content: space-around">
                <el-button plain @click="handleClose">取  消</el-button>
                <el-button type="primary" @click="Submit">确  定</el-button>
            </div>

        </div>

    </el-drawer>
</template>
<script>
    import Sortable from 'sortablejs';
    import {ElMessage} from "element-plus";
    import moment from "moment";
    export default {
        mounted() {

        },
        data() {
            return{
                //后期获取服务端的时间
                ProductDate:[moment(moment().subtract(7, 'days')).format('YYYY/MM/DD'),moment().format('YYYY/MM/DD')],
                OldProductDate:[],
                tableShow:false,
                index:true,
                oldList: [],
                newList: [],
                tableData: [
                    {
                        id:7,
                        name:'李一',
                        epithet:'小李',
                        gender:'男',
                        age:30,
                        job:"会计"
                    },
                    {
                        id:2,
                        name:'王二',
                        epithet:'小王',
                        gender:'未知',
                        age:18,
                        job:"无业游民"
                    },
                    {
                        id:3,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },
                    {
                        id:4,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },{
                        id:7,
                        name:'李一',
                        epithet:'小李',
                        gender:'男',
                        age:30,
                        job:"会计"
                    },
                    {
                        id:2,
                        name:'王二',
                        epithet:'小王',
                        gender:'未知',
                        age:18,
                        job:"无业游民"
                    },
                    {
                        id:3,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },
                    {
                        id:4,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },{
                        id:7,
                        name:'李一',
                        epithet:'小李',
                        gender:'男',
                        age:30,
                        job:"会计"
                    },
                    {
                        id:2,
                        name:'王二',
                        epithet:'小王',
                        gender:'未知',
                        age:18,
                        job:"无业游民"
                    },
                    {
                        id:3,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },
                    {
                        id:4,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },{
                        id:7,
                        name:'李一',
                        epithet:'小李',
                        gender:'男',
                        age:30,
                        job:"会计"
                    },
                    {
                        id:2,
                        name:'王二',
                        epithet:'小王',
                        gender:'未知',
                        age:18,
                        job:"无业游民"
                    },
                    {
                        id:3,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },
                    {
                        id:4,
                        name:'张三',
                        epithet:'小张',
                        gender:'男',
                        age:50,
                        job:"老板"
                    },
                ],
                tableItems: [
                    {
                        id:'01',
                        label: '姓名',
                        list:[
                            {
                                id:'011',
                                label: '现名',
                                prop: 'name',
                            },
                            {
                                id:'012',
                                label: '小名',
                                prop: 'epithet',
                            },
                        ],
                    },
                    {
                        id:'02',
                        label: '性别',
                        prop: 'gender',
                    },
                    {
                        id:'03',
                        label: '年龄',
                        prop: 'age',
                    },
                    {
                        id:'04',
                        label: '工作',
                        prop: 'job',
                    },
                ],
                option:[],
                Moved:false,
                tableOne:[],
                choose:''
            }
        },
        methods: {
            handleChange(time){
                let date=new Date(time[0]).getTime()
                const month=31 * 24 * 3600 * 1000;
                if (date-month<new Date(time[1]).getTime()&&new Date(time[1]).getTime()<date+month){

                }else {
                    // console.log(this.ProductDate)
                    this.ProductDate=JSON.parse(JSON.stringify(this.OldProductDate))
                    ElMessage({
                        message: '只能查询31天的数据',
                        type: 'error',
                    })
                }
            },
            selectTime(){
                this.OldProductDate=JSON.parse(JSON.stringify(this.ProductDate))
            },
            pickerOptionsRang(time) {
                // 禁用当前日期之后的所有日期
                return time.getTime() > Date.now(); // 8.64e7 毫秒数代表一天
            },
            //判断是否修改
            isArrSame(arr1, arr2) {
               return arr1.length === arr2.length && arr1.every((item, index) => arr2.find((it)=>item.id === it.id));
    },
    //确认提交
            Submit(){
                let arr=[]
                // this.option发起请求接口
                this.tableItems.forEach(it=>{
                    let data=this.option.find(item=>{
                        return item.label===it.label
                    })
                    data&&arr.push(data)
                })
               this.tableOne = arr
                //根据回调结果弹出消息
                this.tableShow =false
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
            },
            //抽屉打开的回调函数，后期改为发起请求获取数据
            handleOpen(){
                this.$nextTick(() => {
                    this.Moved=false
                    this.tableOne.forEach(row => {
                        this.$refs.Table.toggleRowSelection(this.tableItems.find(item => { return row.label == item.label }), true)
                    });//toggleRowSelectiond的源码比较有问题，对象引用发生改变，找不到对象
                })
                this.oldList = JSON.parse(JSON.stringify(this.tableOne))
            },
            //抽屉关闭的回调函数，后期改为发起请求修改数据
            handleClose(){
                let change=this.isArrSame(this.oldList,this.option)
                // console.log(!change,this.oldList,this.option,'显示')
                if (this.Moved||!change)//连接后端改为初始获取值
                {
                    this.$confirm('数据未保存是否离开?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    })
                        .then(_ => {
                            this.tableShow=false
                        })
                        .catch(_ => {
                            // this.$refs.Table.clearSelection();//取消全部
                        });
                }else {
                    this.tableShow=false
                }

            },
            Drawers(){
                this.tableShow = true,
                    this.$nextTick(()=>{
                        this.initSortable();
                    })
            },
            handleSelectionChange (val) {
                this.option =val
            },
            MoveUp(index){
                this.Moved=true
                // this.tableData.splice(index - 2, 0, this.tableData[index - 1]);
                if (index > 0) {
                    const item = this.tableItems.splice(index, 1)[0];
                    this.tableItems.splice(index - 1, 0, item);
                }
            },
            Movedown(index){
                this.Moved=true
                if (index <= this.tableItems.length -1) {
                    const item = this.tableItems.splice(index, 1)[0];
                    this.tableItems.splice(index + 1, 0, item);
                }
            },
            initSortable() {
                const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
                Sortable.create(tbody, {
                    handle: '.drag-handle',
                    animation: 100,
                    onEnd: this.onDragEnd,
                });
            },
            onDragEnd(evt) {
                this.Moved=true

                this.$nextTick(()=>{
                    const movedItem = this.tableItems.splice(evt.oldIndex, 1)[0];
                    this.tableItems.splice(evt.newIndex, 0, movedItem);
                    console.log(evt.newIndex,movedItem,this.tableItems,'evt')
                })



            },
            // 行拖拽
            // rowDrop() {
            //     // 此时找到的元素是要拖拽元素的父容器
            //     const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
            //     const _this = this;
            //     if (this.index === true){
            //         Sortable.create(tbody, {
            //             //  指定父元素下可被拖拽的子元素
            //             draggable: ".draggable .el-table__row",
            //             onEnd({newIndex, oldIndex}) {
            //                 const currRow = _this.tableData.splice(oldIndex, 1)[0];
            //                 _this.tableData.splice(newIndex, 0, currRow);
            //                 // console.log(currRow,newIndex,oldIndex,'参数')
            //                 this.index =false
            //                 console.log(this.index)
            //             }
            //         });
            //     }
            //
            // },
        },
        created() {
            this.tableOne = [...this.tableItems]
        }
    }
</script>
<style scoped>
    /deep/.demo-drawer {
        color: #ffffff;
        font-size: 22px;
    }
    /deep/.el-drawer__title{
        justify-content: flex-start;
    }

</style>
